<template>
  <div id="myProgress" class="content">
    <MainPage
      :title="
        pageType === 'index'
          ? '驱动程序库'
          : currentProjectData.displayName + (currentProjectData.chipType === 1 ? '工程' : '驱动')
      "
    >
      <template slot="prefixTitle">
        <el-button
          v-show="pageType === 'openProject'"
          icon="el-icon-arrow-left"
          style="padding: 0; margin-right: 12px"
          type="primary"
          @click="handleBack"
        ></el-button>
      </template>
      <div v-show="pageType === 'index'" class="mainContent">
        <div class="searchDiv">
          列表搜索：
          <el-input
            v-model="search.name"
            placeholder="请输入芯片名称或芯片型号"
            class="searchInput"
            @keyup.enter.native="searchClick"
          ></el-input>
          <el-button type="primary" class="topBtn" @click="searchClick">查询</el-button>
          <el-button class="topBtn" style="padding-left: 0" type="text" @click="clearClick">清空搜索</el-button>
          <el-button
            v-permission="['driverLibraryManagement:driverLibrary:add']"
            style="position: absolute; right: 0"
            type="primary"
            class="topBtn"
            @click="handleClick('add')"
          >
            添加{{ activeName === 'masterChip' ? '主控工程' : '驱动程序' }}
          </el-button>
        </div>
        <el-tabs v-model="activeName" class="tabsContent">
          <el-tab-pane label="主控芯片工程" name="masterChip">
            <chipProject
              ref="chipProject1"
              :chip-type="1"
              :category-list="category.masterChipCategory"
              @handleClick="handleClick"
              @refresh="refreshData"
            />
          </el-tab-pane>
          <el-tab-pane label="被控芯片驱动" name="slaveChip">
            <chipProject
              ref="chipProject2"
              :chip-type="2"
              :category-list="category.slaveChipCategory"
              @handleClick="handleClick"
              @refresh="refreshData"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
      <masterChipDriver
        v-show="pageType === 'openProject' && currentProjectData.chipType === 1"
        ref="masterChipDriver"
        :current-project-data="currentProjectData"
      />
      <slaveChipDriver
        v-show="pageType === 'openProject' && currentProjectData.chipType === 2"
        ref="slaveChipDriver"
        :current-project-data="currentProjectData"
        @refresh="refreshCurrentData"
      />
    </MainPage>
    <tagsView
      ref="tagsView"
      :name="'driver'"
      :tags-data="openProjectData"
      @changePageType="changePageType"
      @closeTag="refresh"
    />
    <driverPrgram ref="driverPrgram" :chip-data="{ masterChipList, slaveChipList }" @submit="refreshData" />
  </div>
</template>

<script>
import chipProject from './components/chipProject.vue'
import {
  loadChipCategoryList,
  loadTreeByCategory,
  getOneSlaveDriverInfo,
  loadDriverLibraryConfig
} from '@/api/project-management'
import defaultSettings from '@/settings'
import { generateUUID, postMessage, receivedMessage } from '@/utils/index'
import tagsView from './components/tagsView'
import slaveChipDriver from './components/slaveChipDriver.vue'
import masterChipDriver from './components/masterChipDriver.vue'
import driverPrgram from './components/driverPrgram.vue'
export default {
  name: 'DriverLibrary',
  components: { chipProject, tagsView, slaveChipDriver, masterChipDriver, driverPrgram },
  data() {
    return {
      pageType: 'index',
      search: { name: '' },
      activeName: 'masterChip',
      category: { masterChipCategory: [], slaveChipCategory: [] },
      masterChipList: [],
      slaveChipList: [],
      getMasterChipRequestId: generateUUID(),
      getSlaveChipRequestId: generateUUID(),
      getChipListRequestId: generateUUID(),
      loadDriverLibraryConfigRequestId: generateUUID(),
      openProjectData: [],
      currentProjectData: { scopeApplicationData: [] }
    }
  },
  created() {
    this.loadCategoryList()
    this.loadMasterChipList()
    this.loadSlaveChipList()
  },
  mounted() {
    this.searchClick()
    receivedMessage(this.dataHandle)
  },
  methods: {
    dataHandle(result) {
      let self = this
      let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
      // 判断消息是否为期望的消息
      if (e.data.webInfo.requestId === self.loadChipCategoryListRequestId) {
        self.category = e.data.response.data
      } else if (e.data.webInfo.requestId === self.getMasterChipRequestId) {
        self.masterChipList = e.data.response.data
      } else if (e.data.webInfo.requestId === self.getSlaveChipRequestId) {
        self.slaveChipList = e.data.response.data
      } else if (e.data.webInfo.requestId === self.loadDriverLibraryConfigRequestId) {
        let res = e.data.response
        if (res.success) {
          self.openProjectWindow(res)
        } else {
          self.$message.error(res.message)
        }
      } else if (e.data.webInfo.requestId === self.refreshCurrentDataRequestId) {
        self.currentProjectData.compatible = e.data.response.data.compatible
        self.currentProjectData.driverDefinitionFiles = e.data.response.data.driverDefinitionFiles
      }
    },
    handleBack() {
      if (this.activeName === 'masterChip') {
        this.$refs.masterChipDriver.closePopover(true)
      }
      this.$refs.tagsView.handleSelectedTag()
    },
    loadCategoryList() {
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.loadChipCategoryListRequestId = generateUUID()
        let message = {
          RequestUrl: process.env.VUE_APP_URL + '/chip/loadChipCategoryList',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: {},
          WebInfo: {
            requestId: this.loadChipCategoryListRequestId
          }
        }
        postMessage(message)
      } else {
        loadChipCategoryList().then((res) => {
          this.category = res.data
        })
      }
    },
    loadMasterChipList() {
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.getMasterChipRequestId = generateUUID()
        let message = {
          RequestUrl: process.env.VUE_APP_URL + '/driverLibrary/loadTreeByCategory',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: { chipType: 1 },
          WebInfo: {
            requestId: this.getMasterChipRequestId
          }
        }
        postMessage(message)
      } else {
        loadTreeByCategory({ chipType: 1 }).then((res) => {
          this.masterChipList = res.data
        })
      }
    },
    loadSlaveChipList() {
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.getSlaveChipRequestId = generateUUID()
        let message = {
          RequestUrl: process.env.VUE_APP_URL + '/driverLibrary/loadTreeByCategory',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: { chipType: 2 },
          WebInfo: {
            requestId: this.getSlaveChipRequestId
          }
        }
        postMessage(message)
      } else {
        loadTreeByCategory({ chipType: 2 }).then((res) => {
          this.slaveChipList = res.data
        })
      }
    },
    refresh(chipType) {
      if (chipType === 1) {
        this.$refs.chipProject1.handleSearch()
      } else {
        this.$refs.chipProject2.handleSearch()
      }
    },
    refreshData(chipType) {
      this.refresh(chipType)
      if (chipType === 1) {
        this.loadMasterChipList()
      }
      // else {
      //   this.loadSlaveChipList()
      // }
    },
    searchClick() {
      this.$refs.chipProject1.refreshData(this.search.name)
      this.$refs.chipProject2.refreshData(this.search.name)
    },
    refreshCurrentData(currentData) {
      new Promise((resolve) => {
        this.refresh(currentData.chipType)
        resolve()
      }).then(() => {
        // 更新当前工程
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          this.refreshCurrentDataRequestId = generateUUID()
          let message = {
            RequestUrl: process.env.VUE_APP_URL + '/driverLibrary/getOneSlaveDriverInfo',
            RequestMethod: 'POST',
            Headers: {
              contentType: 'application/json'
            },
            QueryParameter: {},
            RequestBody: { driverLibraryId: currentData.driverLibraryId },
            WebInfo: {
              requestId: this.refreshCurrentDataRequestId
            }
          }
          postMessage(message)
        } else {
          getOneSlaveDriverInfo({ driverLibraryId: currentData.driverLibraryId }).then((res) => {
            this.currentProjectData.compatible = res.data.compatible
            this.currentProjectData.driverDefinitionFiles = res.data.driverDefinitionFiles
          })
        }
      })
    },
    clearClick() {
      this.search.name = ''
      this.searchClick()
    },
    handleClick(name, row = {}) {
      if (name === 'add') {
        this.$refs.driverPrgram.is(name, {
          chipType: this.activeName === 'masterChip' ? 1 : 2,
          chipId: '',
          driverDefinitionFiles: []
        })
      } else if (name === 'open') {
        let isOpen = this.openProjectData.findIndex((item) => item.driverLibraryId === row.driverLibraryId)
        if (isOpen === -1) {
          this.currentRow = {
            open: false,
            saved: true,
            ...row,
            projectId: row.driverLibraryId,
            name: row.displayName
          }

          if (defaultSettings.isWPF || defaultSettings.isCEF) {
            this.loadDriverLibraryConfigRequestId = generateUUID()
            let message = {
              RequestUrl:
                process.env.VUE_APP_URL +
                (this.activeName === 'masterChip'
                  ? '/driverLibraryConfig/loadConfig'
                  : '/driverLibrary/getOneSlaveDriverInfo'),
              RequestMethod: 'POST',
              Headers: {
                contentType: 'application/json'
              },
              QueryParameter: {},
              RequestBody: { driverLibraryId: row.driverLibraryId },
              WebInfo: {
                requestId: this.loadDriverLibraryConfigRequestId
              }
            }
            postMessage(message)
          } else {
            let operation = this.activeName === 'masterChip' ? loadDriverLibraryConfig : getOneSlaveDriverInfo
            operation({ driverLibraryId: row.driverLibraryId }).then((res) => {
              this.openProjectWindow(res)
            })
          }
        } else {
          this.$refs.tagsView.handleSelectedTag({ ...row, projectId: row.driverLibraryId })
        }
      }
    },
    openProjectWindow(res) {
      if (this.activeName === 'masterChip') {
        this.currentRow.cSource = res.data.cSource
        this.currentRow.hHeader = res.data.hHeader
        this.currentRow.otherDriver = res.data.otherDriver
        this.currentRow.driverDocumentation = res.data.driverDocumentation
        this.currentRow.clockTemplate = res.data.clockTemplate
      } else {
        this.currentRow = {
          open: false,
          saved: true,
          ...res.data,
          projectId: res.data.driverLibraryId,
          name: res.data.displayName,
          driverFile: res.data.hHeaderFiles
            .concat(res.data.cSourceFiles, res.data.driverDocumentationFiles, res.data.otherDriverFiles)
            .map((item) => {
              return {
                ...item,
                fileName: item.fileName.split('.')[0],
                editable: false
              }
            })
        }
      }
      // this.currentRow.templateFile = res.data.templateFile
      // this.currentRow.driverFile = res.data.hHeaderFile.concat(res.data.cSourceFile).map((item) => {
      //   return {
      //     ...item,
      //     fileName: item.fileName.split('.')[0],
      //     editable: false
      //   }
      // })
      this.openProjectData.push(this.currentRow)
      this.$refs.tagsView.handleSelectedTag(this.currentRow)
    },
    changePageType(val, oldValue) {
      if (this.activeName === 'masterChip') {
        this.$refs.masterChipDriver.closePopover(true)
      }
      if (val) {
        this.pageType = 'openProject'
        this.currentProjectData = this.openProjectData.find((item) => item.driverLibraryId === val)
        if (!this.currentProjectData.open) {
          let index = this.openProjectData.findIndex((item) => item.driverLibraryId === val)
          this.openProjectData[index].open = true
          this.$nextTick(() => {
            this.$refs[this.activeName + 'Driver'].init()
          })
        } else {
          this.$nextTick(() => {
            this.$refs[this.activeName + 'Driver'].init(true)
          })
        }
      } else {
        this.pageType = 'index'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.content {
  height: 100%;
  display: flex;
  flex-direction: column;
  color: #333;
  /deep/.main {
    padding: 0;
  }
  .mainContent {
    flex: 1;
    height: calc(100% - 15px);
    padding: 0 24px;
    .searchDiv {
      margin-bottom: 10px;
      position: relative;
      .searchInput {
        width: 240px;
        padding-right: 0;
        margin-right: 15px;
      }
    }
    .tabsContent {
      height: calc(100% - 42px);

      /deep/.el-tabs__content {
        height: calc(100% - 55px);
        .el-tab-pane {
          height: 100%;
        }
      }
    }
  }
}
</style>
